import json
from flask_restful import Resource
from comment.models.goods import Product
from comment.models.index import *
from comment.utils.data2dict import datalist2dict, data2dict
from comment.utils.shopping_redis import redis_client


# 商品分类的资源类
class Shopping_Category(Resource):

    def get(self):
        # 1.从redis读取数据
        data_cache = redis_client.get("index_category")
        if data_cache:  # 2.如果redis中有数据，则返回redis中的数据
            print(type(data_cache))  # 测试
            return json.loads(data_cache)
        else:  # 3.redis中没有数据，则查询mysql数据库，把查询结果写入到redis,并返回数据
            data = self.getData(0)
            if data:
                for item in data:
                    item.update({'list': ''})
                    data_second = self.getData(int(item['id']))  # 二级分类
                    item['list'] = data_second
                    for item1 in data_second:
                        item1.update({'list': ''})
                        data_third = self.getData(int(item1['id']))  # 三级分类
                        item1['list'] = data_third
                # 将查询数据写入redis
                redis_client.setex("index_category", 3600 * 24, json.dumps(data))  # 将数据序列化为bytes，存入数据库
                return data
            else:
                return {'message': 'none'}

    # 获取分类数据的静态方法
    @staticmethod
    def getData(parent_id):
        res = Category.query.with_entities(Category.id, Category.parent_id, Category.name).filter(
            Category.parent_id == parent_id).order_by(Category.sort.asc()).limit(10).all()  # 部分查询，选择，排序

        if res:
            return datalist2dict(res)
        else:
            return 'none'


# 新品推荐
class Shopping_HomeNewProduct(Resource):
    def get(self):
        # res = HomeNewProduct.query.limit(10).all()
        res = HomeNewProduct.query.join(Product, HomeNewProduct.product_id == Product.id).with_entities \
            (Product.id, Product.default_pic, Product.price, Product.product_name, Product.rel_category3_id).limit(
            10).all()
        if res:
            data = datalist2dict(res)
            return data
        else:
            return {'message': 'none'}


# 首页人气热搜的资源类
class Shopping_HomeRecommendProduct(Resource):
    def get(self):
        # 从redis读取数据
        data_cache = redis_client.get("index_HomeRecommendProduct")
        if data_cache:  # 如果redis中有数据，则返回redis中的数据
            return json.loads(data_cache)
        else:  # redis中没有数据，则查询mysql数据库，把查询结果写入到redis,并返回数据
            res = HomeRecommendProduct.query.join(Product, HomeRecommendProduct.product_id == Product.id).with_entities \
                (Product.id, Product.default_pic, Product.price, Product.product_name, Product.rel_category3_id).limit(
                10).all()
            if res:
                data = datalist2dict(res)
                # 将查询数据写入redis
                redis_client.setex("index_HomeRecommendProduct", 3600 * 24, json.dumps(data))
                return data
            else:
                return {'message': 'none'}


# 后台广场
class Shopping_RecommendSubject(Resource):
    def get(self):
        data_cache = redis_client.get('index_RecommendSubject')
        if data_cache:
            return json.loads(data_cache)
        else:
            res = CmsSubject.query.filter(CmsSubject.show_status == 1).all()
            res_list = []
            for res_obj in res:
                if res_obj:
                    data = data2dict(res_obj)
                    res_product = CmsSubjectProductRelation.query.join \
                        (Product, CmsSubjectProductRelation.product_id == Product.id).filter \
                        (CmsSubjectProductRelation.subject_id == res_obj.id).with_entities \
                        (Product.id, Product.default_pic, Product.price, Product.product_name,
                         Product.rel_category3_id).limit(10).all()
                    if res_product:
                        data_product = datalist2dict(res_product)
                        data['productList'] = data_product
                        res_list.append(data)
            if len(res_list) > 0:
                print(res_list)
                # 向redis写入数据
                redis_client.setex('index_RecommendSubject', 3600 * 24, json.dumps(res_list))  # 转换成bytes写给数据库
                return res_list
            else:
                return {'message': 'none'}


    # def get(self):
    #     res = CmsSubject.query.filter(
    #         CmsSubject.show_status == 1).all()
    #
    #     res_list = []
    #     for res_obj in res:
    #         if res_obj:
    #             data = data2dict(res_obj)
    #             res_product = CmsSubjectProductRelation.query.join \
    #                 (Product, CmsSubjectProductRelation.product_id == Product.id).filter \
    #                 (CmsSubjectProductRelation.subject_id == res_obj.id).with_entities \
    #                 (Product.id, Product.default_pic, Product.price, Product.product_name,
    #                  Product.rel_category3_id).limit(10).all()
    #             if res_product:
    #                 data_product = datalist2dict(res_product)
    #                 data['productList'] = data_product
    #                 res_list.append(data)
    #     if len(res_list) > 0:
    #         print(res_list)
    #         return res_list
    #     else:
    #         return {'message': 'none'}


class DictTest(Resource):
    def get(self):
        # res = Category.query.filter(Category.parent_id==0).all()
        res = Category.query.with_entities(Category.id, Category.name).filter(Category.parent_id == 0).all()
        if res:
            return datalist2dict(res)
        else:
            return 'none'
